package com.lagou.edu.wwyan.web1.minicat;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

public class Connector implements LifeCycle{
    private int port = 8080;
    private Mapper mapper;

    public Mapper getMapper() {
        return mapper;
    }

    public void setMapper(Mapper mapper) {
        this.mapper = mapper;
    }

    public Connector(int port) {
        this.port = port;
    }

    public Connector() {
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    @Override
    public void init() {
        System.out.println("connector init");
    }

    @Override
    public void start() throws Exception {
        System.out.println("connector start");
        ServerSocket serverSocket = new ServerSocket(port);

        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        while (true){
            Socket socket = serverSocket.accept();
//            RequestProcessor processor = new RequestProcessor(socket,servletMap);
            RequestProcessor processor = new RequestProcessor(socket,mapper);
            threadPoolExecutor.execute(processor);
        }
    }
}
